# coding: utf8
import MySQLdb
from warnings import filterwarnings
filterwarnings('ignore', category = MySQLdb.Warning)


def create_ssh_server(**kwags):
	"""创建ssh通道服务

	:param remote_ip_address: SSH远程中转服务器ip地址
	:param ssh_port: SSH远程服务器连接端口
	:param ssh_username: 远程服务器用户名
	:param ssh_passwd: 远程服务器密码
	:param remote_db_address: 数据库地址
	:param remote_db_port: 数据库端口号
	Usage:
		server = create_ssh_server(**kwags)
		server.start()
		port = server.local_bind_port
		...MYSQL Connection...
		server.close()
	"""
	from sshtunnel import SSHTunnelForwarder
	
	remote_ip_address = kwags.get('remote_ip_address', '')
	ssh_port = kwags.get('ssh_port', 22)
	ssh_username = kwags.get('ssh_username', '')
	ssh_passwd = kwags.get('ssh_passwd', '')
	remote_db_address = kwags.get('remote_db_address', '')
	remote_db_port = kwags.get('remote_db_port', 3306)
	
	return SSHTunnelForwarder(
			(remote_ip_address, int(ssh_port)),
			ssh_password=ssh_passwd,
			ssh_username=ssh_username,
			remote_bind_address=(remote_db_address, int(remote_db_port))
			)


def div_list_2(ls, n):
	"""
	等分切割列表,
	n : 切割的大小
	"""
	len_ls = len(ls)
	times = len_ls/n 	# 组数
	last_num = len_ls%n # 最后一次

	datas = []
	if times == 0:
		datas.append(ls)
	else:
		num = 0
		for i in range(times):
			datas.append(ls[i*n:(i+1)*n])
		if last_num > 0:
			datas.append(ls[-last_num:])
	return datas


def select_description(conn, sql):
	"""
	Function doc
	读取数据库表字段名和字段值
	"""
	cur = conn.cursor()		# 创建实例
	item = {}
	try:
		cur.execute(sql)
		data = cur.fetchall()
		description = cur.description 	# 字段描述
		item['data'] = data
		item['description'] = description
	except MySQLdb.Error as e:
		print ('MysqlError %s : %s' % (e[0],  e[1]))
	cur.close()		# 关闭实例

	return item

